package com.tarena.lbs.user.dao.repository.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import com.tarena.lbs.user.dao.mapper.UserGroupMapper;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.pojo.param.UserGroupParam;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import com.tarena.lbs.user.pojo.vo.UserGroupVO;
import com.tarena.lbs.user.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class UserGroupRepositoryImpl implements UserGroupRepository {
    @Autowired
    private UserGroupMapper userGroupMapper;
    @Autowired
    private AdminService adminService;


    @Override
    public void save(UserGroupParam userGroupParam) throws BusinessException {
        log.debug("保存人群数据,入参:{}",userGroupParam);
        //需要获取当前登录商家的id
        //1.解析jwt 拿到userPrinciple
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        Integer userId = userPrinciple.getId();
        AdminDto detail = adminService.detail(userId);
        log.debug("当前用户的信息:{}",detail);

        UserGroupPO userGroupPO = new UserGroupPO();
        BeanUtils.copyProperties(userGroupParam,userGroupPO);
        userGroupPO.setCreateAt(new Date());
        userGroupPO.setBusinessId(detail.getBusinessId());
        if(userGroupPO.getId()==null){
            userGroupMapper.insert(userGroupPO);
        }else{
            userGroupMapper.updateById(userGroupPO);
        }

    }

    @Override
    public PageResult<UserGroupVO> pageList(UserGroupQuery query) {
        // 使用 MyBatis-Plus 分页支持
        Page<UserGroupPO> page = new Page<>(query.getPageNo(), query.getPageSize());
        // 构建查询条件
        QueryWrapper<UserGroupPO> wrapper = new QueryWrapper<>();
        // 添加状态不等于2的条件（排除删除状态）
        wrapper.ne("status", 2);

        // 根据status查询启用禁用状态
        if (query.getStoreHeadPhone() != null) {
            wrapper.eq("status", query.getStoreHeadPhone());
        }

        if (query.getStoreName() != null && !query.getStoreName().isEmpty()) {
            wrapper.like("group_name", query.getStoreName());
        }
        // 执行分页查询
        Page<UserGroupPO> result = userGroupMapper.selectPage(page, wrapper);
        // 转换 PO 到 VO
        List<UserGroupVO> userGroupVOS = result.getRecords().stream()
                .map(po -> {
                    UserGroupVO vo = new UserGroupVO();
                    BeanUtils.copyProperties(po, vo);
                    // 处理时间转换等特殊字段
                    if (po.getCreateAt() != null) {
                        vo.setCreateAt(po.getCreateAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    }
                    return vo;
                })
                .collect(Collectors.toList());
        // 封装分页结果
        PageResult<UserGroupVO> pageResult = new PageResult<>();
        pageResult.setPageNo((int) result.getCurrent());
        pageResult.setPageSize((int) result.getSize());
        pageResult.setTotal(result.getTotal());
        pageResult.setObjects(userGroupVOS);
        return pageResult;
    }




    @Override
    public UserGroupParam detail(UserGroupParam param) {
        // 从 param 中获取 id
        Integer id = param.getId();
        // 根据 id 查询
        UserGroupPO userGroupParamOptional = userGroupMapper.selectById(id);
        // 如果查询到，返回结果；
            UserGroupParam userGroupParam = new UserGroupParam();
            BeanUtils.copyProperties(userGroupParamOptional, userGroupParam);
            return userGroupParam;
    }

    @Override
    public void update(UserGroupParam param) {
        //点击状态修改状态
        userGroupMapper.updateStatus(param);
    }

    @Override
    public void delete(UserGroupParam param) {
        userGroupMapper.deleteStatus(param);
    }


}
